package com.kgc.sbt.controller;

import javax.servlet.http.HttpServletRequest;

/**
 * Created on 2021-06-16.
 * <p>
 * Author:
 * <p>
 * Description: 请求控制器的基类，包含一些通用方法
 */
public class BaseController {

    /**
     * @author :
     * @date : 2021-06-16
     * @return :
     * @description : 从request获取参数，获取不到，直接置空字符串
     */
    protected String getParameter(HttpServletRequest request, String key){
        return request.getParameter(key) == null ? "" : request.getParameter(key);
    }

    /**
     * @author :
     * @date : 2021-06-16
     * @return :
     * @description : 从request获取参数，获取不到，直接指定默认值
     */
    protected String getParameterUseDefValue(HttpServletRequest request, String key, String defValue){
        return request.getParameter(key) == null ? defValue : request.getParameter(key);
    }

    /**
     * @author :
     * @date : 2021-06-16
     * @return :
     * @description : 根据请求，获取请求ip
     */
    protected String getRemoteIp(HttpServletRequest request) {
        // 获取ip
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }
}
